var http = require('http')
var url = require('url')
var path = require('path')
var fs = require('fs')
var mime = require('./mime.js').types
var config  = require('./config.js')
var port = 9000

var server = http.createServer((request, response) => {
    var pathname = url.parse(request.url).pathname
    var realpath = 'assets' + pathname
    var ext = path.extname(realpath)
    ext = ext ? ext.slice(1) : 'unknown'
    var contentType =  mime[ext] || 'text/plain'

    if (ext.match(config.Expires.fileMatch)) {
        console.log("matched")
        var expires = new Date()
        expires.setTime(expires.getTime() + config.Expires.maxAge * 1000)
        response.setHeader('Expires', expires.toUTCString())
        response.setHeader('Cache-Control', 'max-age=' + config.Expires.maxAge)
    }
    fs.stat(realpath, function(err, stat) {
        var lastModified = stat.mtime.toUTCString()
        response.setHeader('Last-Modified', lastModified)
        if (request.headers['if-modified-since'] 
            && lastModified === request.headers['if-modified-since']) {
            response.writeHead(304, 'Not Modified')
            response.end()
        } else  {
            fs.exists(realpath, function(exists) {
                if (!exists) {
                    response.writeHead(404, {
                        'Content-Type': 'text/plain'
                    })
        
                    response.write('404 NOT FOUND')
                    response.end()
                } else  {
                    fs.readFile(realpath, 'binary', function(err, file) {
                        if (err) {
                            response.writeHead(500, {
                                'Content-Type': 'text/plain'
                            })
                            response.end()
                        } else {
                            response.write(file, 'binary')
                            response.end()
                        }
                    })
                }
            })
        }
    })
    
})

server.listen(port, function() {
    console.log("success running at " + port)
})